﻿namespace Services.Implement;

public class AVCUMService
{
    private static string? token { get; set; }
    public static string tokenKey = "avcumplatform_token";
    /// <summary>
    /// 来源
    /// </summary>
    public static string Source = string.Empty;

    /// <summary>
    /// 认证
    /// </summary>
    public static async Task GetToken()
    {
        var res = new ResultModel();
        try
        {
            var host = AppSetting.configModel.UMPlatformConfig.Host;
            if (string.IsNullOrWhiteSpace(host))
            {
                return;
            }
            if (RedisStaticHelper.Exists(tokenKey))
            {
                token = await RedisStaticHelper.GetAsync<string>(tokenKey);
            }
            else
            {
                var obj = new
                {
                    AppSetting.configModel.UMPlatformConfig.AK,
                    AppSetting.configModel.UMPlatformConfig.SK
                };
                var ret = await HTTPHelper.Post<ResultModel>($"{host}/api/Authentication/GetToken", obj);
                if (ret != null)
                {
                    token = ret.data;
                    if (!string.IsNullOrWhiteSpace(token))
                    {
                        await RedisStaticHelper.SetAsync(tokenKey, token);
                    }
                }
            }

        }
        catch (Exception ex)
        {
            if (res != null)
            {
                Log.Write($"统一消息平台认证失败:{JsonConvert.SerializeObject(res)}");
            }
            Log.WriteException(ex);
        }
    }

    /// <summary>
    /// 获取消息模板json
    /// </summary>
    public static async Task<string?> GetMessageTmplateJson(string msgTypeCode)
    {
        var res = new ResultModel();
        var sendJson = string.Empty;
        var host = AppSetting.configModel.UMPlatformConfig.Host;
        try
        {
            if (string.IsNullOrWhiteSpace(host))
            {
                return sendJson;
            }
            await GetToken();
            res = await HTTPHelper.Get<ResultModel>($"{host}/api/MessageTypes/GetDetailByCode?code={msgTypeCode}", token);
            if (res != null)
            {
                sendJson = res.data;
            }
        }
        catch (Exception ex)
        {
            // token 过期重试
            if (ex.Message.Contains("401"))
            {
                RedisStaticHelper.Remove(tokenKey);
                await GetToken();
                res = await HTTPHelper.Get<ResultModel>($"{host}/api/MessageTypes/GetDetailByCode?code={msgTypeCode}", token);
            }
            if (res != null)
            {
                Log.Write($"获取消息模板json失败:{JsonConvert.SerializeObject(res)}");
            }
            Log.WriteException(ex);
        }
        return sendJson;
    }

    public static async Task SendMsg(MessagequeuesReq messagequeues)
    {
        var host = AppSetting.configModel.UMPlatformConfig.Host;
        if (string.IsNullOrWhiteSpace(host))
        {
            return;
        }
        var result = new ResultModel();
        var sendObj = new Messagequeues();
        try
        {
            await GetToken();
            var msgType = messagequeues.Msgtype;
            sendObj.Msgtype = msgType;
            var sendJson = await GetMessageTmplateJson(msgType);
            if (string.IsNullOrWhiteSpace(sendJson))
            {
                Log.Write($"发送统一消息失败:消息模板json为空，token:{token}");
                return;
            }
            sendObj.Source = Source;
            sendJson = sendJson.Replace("{{userPhones}}", messagequeues.ContentObj.UserPhones);
            sendJson = sendJson.Replace("{{content}}", messagequeues.ContentObj.Content);
            sendJson = sendJson.Replace("{{userIds}}", "");
            sendObj.Content = sendJson;
            result = await HTTPHelper.Post<ResultModel>($"{host}/api/Message/Send", sendObj, token);
            if (result != null && result.code < 0)
            {
                Log.Write($"发送统一消息失败:{JsonConvert.SerializeObject(result)}，token:{token}");
            }
        }
        catch (Exception ex)
        {
            // token 过期重试
            if (ex.Message.Contains("401"))
            {
                RedisStaticHelper.Remove(tokenKey);
                await GetToken();
                result = await HTTPHelper.Post<ResultModel>($"{host}/api/Message/Send", sendObj, token);
            }
            if (result != null)
            {
                Log.Write($"发送统一消息失败:{JsonConvert.SerializeObject(result)}，token:{token}");
            }
            Log.WriteException(ex);
        }

    }
}
